

<script lang="ts" setup>
import { reactive, ref ,onMounted} from 'vue'
import type { FormProps } from 'element-plus'
import { checkusernameservice} from '../api/user.js'
import {sendVerificationCodeservice} from '../api/user.js'
import {submituserservice} from '../api/user.js'
import {loginserice} from "../api/user.js";
import axios from '../request.js';
import {captchaservice} from "../api/user.js"
import router from "../router.js"
const labelPosition = ref<FormProps['labelPosition']>('right')
const isRegister = ref(false)
const formLabelAlign = reactive({
  username: '',
  password: '',
  repassword: '',
  usernameAvailable: false,
  messageText: '',
  passwordMessage: '',
  passwordValid: false,
  sex:'',
  age:'',
  phone:'',
  adress:'',
  idCard:'',
  idCardvalid:false,
  idCardtext:'',
  verificationCode:'',
  email:'',
  emliytext:'',
  emilyvalid:false,
  registervalid:false,
  regisertext:'',
  showSuccessPopup: false,
  showErrorPopup: false,
  errorMessage: '', // 存储错误信息
})
const registerdata = reactive(
    {
      username: '',
      password: '',
      sex:'',
      age:18,
      phone:'',
      adress:'',
      idCard:'',
      email:'',
      verificationCode:''
    }

)
const formInline = reactive(
    {
      username:'',
      password:'',
      captcha: ''

    }
)
const  errorMessage=ref('');
const  captchaImageUrl=ref('');
const value = ref('')
const options = [
  {
    value: '男',
    label: '男',
  },
  {
    value: '女',
    label: '女',
  }

]
const imageurl =[
  'https://img.zcool.cn/community/01e0015bdc140ba80121ab5d69a7a3.jpg@1280w_1l_2o_100sh.jpg',
    'https://img.zcool.cn/community/01a23d5867aa8fa801219c7778c309.jpg@1280w_1l_2o_100sh.jpg',
    'https://img.zcool.cn/community/019c2e5e3996d6a801216518a20a0f.jpg@2o.jpg'

]
const checkUsernameExistence = async () => {
  console.log(11111111111);

  if (registerdata.username === '') {
    formLabelAlign.usernameAvailable = false;
    formLabelAlign.messageText = '用户名不能为空';
  } else {
    try {
      const response = await checkusernameservice(registerdata.username);
      formLabelAlign.usernameAvailable = response. code === 200;
      formLabelAlign.messageText = formLabelAlign.usernameAvailable ? '用户名可用' : '用户名重复';
    } catch (error) {
      console.error('查询失败:', error);
      formLabelAlign.messageText = '查询失败';
    }

  }}
const checkPasswordMatch = async ()  => {
  console.log('this.password:', registerdata.password);
  console.log('this.repassword:', formLabelAlign.repassword);

  if (registerdata.password === '' || formLabelAlign.repassword === '') {
    console.log('进入密码为空的分支');
    formLabelAlign.passwordValid = false;
    formLabelAlign.passwordMessage = '密码或重复密码都不能为空';
  } else {
    console.log('进入密码比较的分支');
    if (registerdata.password === formLabelAlign.repassword) {
      formLabelAlign.passwordValid = true;
      formLabelAlign.passwordMessage = '密码一致';
    } else {
      formLabelAlign.passwordValid = false;
      formLabelAlign.passwordMessage = '两次密码不一致';
    }
  }
}
const  checkIdCard= async ()  => {
  // 身份证号码的正则表达式
  const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;

  if (registerdata.idCard.length !== 18 || !idCardRegex.test(registerdata.idCard)) {
    // 如果身份证号码长度不为18位或者格式不符合规范
    console.log('身份证号码不合法');
    formLabelAlign.idCardvalid=false
    formLabelAlign.idCardtext='身份证号码不合法'
  } else {
    // 身份证号码合法
    console.log('身份证号码合法');
    formLabelAlign.idCardvalid=true
    formLabelAlign.idCardtext='身份证号码合法'
  }
}
const  sendVerificationCode = async () => {
  // 检查邮箱格式
  const emailPattern = /^\w+([-+.]?\w+)*@qq\.com$/;
  if (!emailPattern.test(registerdata.email)) {
    console.error('邮箱格式不合法');
    formLabelAlign.emliytext = '邮箱格式不合法，请输入正确的邮箱';
    formLabelAlign.emilyvalid = false;
    return;
  }

  try {
    const response = await sendVerificationCodeservice(registerdata.email);
    if (response.code === 200) {
      console.log('验证码发送成功');
      formLabelAlign.emliytext = '验证码发送成功';
      formLabelAlign.emilyvalid = true;
    }
  } catch (error) {
    console.error('验证码发送失败:', error);
    formLabelAlign.emliytext = '验证码发送失败，请重新发送';
    formLabelAlign.emilyvalid = false;
  }
}

const submituser = async () => {
  try {

    // 发送注册请求
    const response = await submituserservice(registerdata);

    // 根据后端返回的数据处理注册结果
    if (response.code === 200) {
      console.log('注册成功');
      isRegister.value=false;
    } else {
      console.error('注册失败:', response.message);
      formLabelAlign.errorMessage = response.message; // 存储后端返回的错误信息
      formLabelAlign.showErrorPopup = true; // 显示注册失败弹窗
    }
  } catch (error) {
    console.error('注册失败:', error);
    formLabelAlign.errorMessage = '注册失败，请稍后再试'; // 设置默认错误信息
    formLabelAlign.showErrorPopup = true; // 显示注册失败弹窗
  }
}
const refreshCaptcha= async()=>{
  try {
    const response = await captchaservice();
    captchaImageUrl.value = URL.createObjectURL(response);
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
}
const login= async() =>  {
  try {
    const response = await loginserice(formInline);

    if (response.code === 200) {
      console.log('登录成功');

      const token = response.token; // 假设后端返回的数据中令牌字段名为token
      if(response.token==null){
        console.log("token令牌为空");

      }
      console.log(token);
      localStorage.setItem('token', token); // 将令牌存储在本地存储中
      // 将令牌添加到 Axios 的默认请求头中
      axios.defaults.headers.common['Authorization'] = `${token}`;
      await router.push("/index")
    } else {
     errorMessage.value = response.message;
      await refreshCaptcha(); // 登录失败时刷新验证码
    }
  } catch (error) {
    console.error('登录失败:', error);
  }
}
const chageisLogin=()=>{
  isRegister.value=true;

}
onMounted(() => {
  refreshCaptcha(); // 在组件挂载时调用刷新验证码的方法
});
</script>
<template>

  <div class="backgronund-div">
    <el-container class="el-container1">
      <el-aside width="600px" >
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="(imageurl, index) in imageurl" :key="index" >
            <img :src="imageurl" :alt="'Image ' + (index + 1)" style="width: 100%; height: 100%;" />
          </el-carousel-item>
        </el-carousel>
      </el-aside>
      <el-container>
        <el-header class="login-title">Login</el-header>
        <el-main>

          <div style="margin: 20px" />
          <el-form v-if="isRegister"
                   :label-position="labelPosition"
                   label-width="auto"
                   :model="registerdata"
                   class="register-form"
          >
            <el-form-item label="用户名">
              <el-input v-model="registerdata.username" @blur="checkUsernameExistence" />
              <div class="message" :class="{ 'available': formLabelAlign.usernameAvailable, 'duplicate': !formLabelAlign.usernameAvailable }">
                {{ formLabelAlign.messageText }}
              </div>
            </el-form-item>
            <el-form-item label="密码"   >
              <el-input v-model="registerdata.password" type="password" @blur="checkPasswordMatch"/>
            </el-form-item>
            <el-form-item label="确认密码"  >
              <el-input v-model="formLabelAlign.repassword" type="password" @blur="checkPasswordMatch" />
            </el-form-item>
            <!-- 其他表单项 -->
            <el-form-item label="邮箱" >
              <el-input v-model="registerdata.email" />
              <div class="emily-message" :class="{ 'match':  formLabelAlign.emilyvalid, 'mismatch': ! formLabelAlign.emilyvalid }">
                {{ formLabelAlign.emliytext }}
              </div>
            </el-form-item>
            <el-form-item label="验证码" >
              <el-input v-model="registerdata.verificationCode" />
            </el-form-item>
            <el-button type="success" @click="sendVerificationCode">发送验证码</el-button>
            <el-button type="success" @click="submituser">注册</el-button>
          </el-form>


          <el-form :inline="true" :model="formInline" class="demo-form-inline" id="login-form" v-else >
            <el-form-item label="用户名" class="login-label" label-width="60px">
              <el-input v-model="formInline.username" placeholder="请输入用户名" clearable class="login-input" />
            </el-form-item>
            <el-form-item label="密码" class="login-label" label-width="60px">
              <el-input v-model="formInline.password" placeholder="请输入密码" clearable id="login-input-pwd" class="login-input" type="password" />
            </el-form-item>
            <el-form-item label="验证码" class="login-label" label-width="60px">
              <el-input v-model="formInline.captcha" placeholder="请输入验证码" clearable class="login-input" />
              <img :src="captchaImageUrl" @click="refreshCaptcha" alt="验证码"  id="code" class="code-img">
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
            <span class="register-link" @click="chageisLogin">注册-></span>
          </el-form>
          <div v-if="errorMessage" class="error">{{ errorMessage }}</div>


        </el-main>
      </el-container>
    </el-container>


  </div>



</template>



<style scoped>
.available::after {
  background-color: green;
}



.password-message {
  margin-top: 10px;
}

.match {
  color: green;
}

.mismatch {
  color: red;
}
.message {
  position: relative;
  display: inline-block;
  margin-left: 10px;
}

.message::after {
  content: '';
  position: absolute;
  top: 0;
  right: -20px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
 .el-carousel__item h3 {
   color: #475669;
   opacity: 0.75;
   line-height: 200px;
   margin: 0;
   text-align: center;
 }
.el-container1 {
  position: absolute;
  display: flex;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}


.backgronund-div{
  background-color: #717875;
  background-image: linear-gradient(to bottom right,#747977,#a5c5b7);
  height: 600px;
  width: 1200px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
#code{
  width: 100px;
}
.demo-form-inline {
  width: 300px;
}
.demo-form-inline el-form-item {
  padding-left: 50px;
}
/*.demo-form-inline el-form-item el-input{*/
/*  width: 250px;*/
/*}*/
.login-input label {
  width: 45px;
}
.login-input {
  width: 200px;
  margin-left: 10px;
  box-sizing: border-box;
}
#login-input-pwd {
  width: 250px;
}
.login-label {
  /*label-width: 50px;*/
}
.login-title{
  font-size: 60px;
  font-weight:bold;
  font-family: 隶书 ;

}
.code-img{
  margin-left: 10px;
  margin-top: 5px;
}
.register-form {
  width: 400px;
  padding: 20px;
  background-color: #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.register-form .el-form-item {
  margin-bottom: 20px;
}

.register-form .message {
  margin-top: 5px;
  color: #999;
}

.register-form .available {
  color: green;
}

.register-form .duplicate {
  color: red;
}

.register-form .password-message {
  margin-top: 5px;
  color: #999;
}

.register-form .match {
  color: green;
}

.register-form .mismatch {
  color: red;
}

.register-form .emily-message {
  margin-top: 5px;
  color: #999;
}

.register-form .emily-message .match {
  color: green;
}

.register-form .emily-message .mismatch {
  color: red;
}
#login-form {
  width: 400px;
  padding: 20px;
  background-color: #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.register-link {
  color: #666;
  cursor: pointer;
  transition: color 0.3s; /* 添加过渡效果，使颜色变化更平滑 */
}

.register-link:hover {
  color: #007bff; /* 鼠标悬停时变色 */
}
</style>